<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WebRTC Video Stream</title>
</head>
<body>
<video id="remoteVideo" autoplay playsinline></video>
<script >
const videoElement = document.getElementById('remoteVideo');
let peerConnection;
let ws;

function setupWebSocket() {
  ws = new WebSocket('ws://localhost:8765');
  ws.onmessage = function(message) {
    const data = JSON.parse(message.data);
    if (data.sdp) {
      peerConnection.setRemoteDescription(new RTCSessionDescription(data))
        .then(() => {
          if (data.type === 'offer') {
            return peerConnection.createAnswer();
          }
        })
        .then(answer => peerConnection.setLocalDescription(answer))
        .then(() => {
          ws.send(JSON.stringify({'sdp': peerConnection.localDescription.sdp, 'type': peerConnection.localDescription.type}));
        })
        .catch(error => console.error(error));
    } else if (data.candidate) {
      // No need to handle ICE candidates via WebSocket, WebRTC handles it automatically
    }
  };
}

function setupPeerConnection() {
  peerConnection = new RTCPeerConnection();

  peerConnection.ontrack = function(event) {
    if (event.track.kind === 'video') {
      videoElement.srcObject = event.streams[0];
    }
  };

  peerConnection.onicecandidate = function(event) {
    if (event.candidate) {
      // No need to send ICE candidate via WebSocket, WebRTC handles it automatically
    }
  };
}

function start() {
  setupPeerConnection();
  setupWebSocket();

  peerConnection.createOffer()
    .then(offer => peerConnection.setLocalDescription(offer))
    .then(() => {
      ws.send(JSON.stringify({'sdp': peerConnection.localDescription.sdp, 'type': peerConnection.localDescription.type}));
    })
    .catch(error => console.error(error));
}

start();

</script>
</body>
</html>
